var app = getApp()
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var utils = require('../../utils/utils');
var comment = require('../widget/comment/comment');
var storage = require('../../utils/storage');
var filter = require('../widget/filter');
var formatTime = require('../widget/time');
var commentList = require('../widget/commentList');
var goTop = require('../widget/goTop/goTop');
var timestamp = require('../widget/timestamp');

var mark = 0;
var pageSetting = {
  //留言各种操作的回调函数
  callback: function (componentName) {
    var that = this;
    switch (componentName) {
      case 'commentContent':
        var commentData = that.data['commentData'];
        commentFun(commentData, arguments[1]);
        break;
      case 'likeFun':
        var likeData = arguments[1];
        like(likeData);
        break;
      case 'delcommentFun':
        var delData = arguments[1];
        delcommentFun(delData);
        break;
      case 'removeBindtapFun':

        var removeFlag = arguments[1];
        removeBindtapFun(removeFlag);
        break;
      case 'delStairComment':
        delStairComment(arguments[1]);
        break;
      case 'delSecondComment':
        delSecondComment(arguments[1]);
        break;
      case 'pullUpLoad':
        pullUpLoad();
        break;
      case 'onCommentShow':
        removeBindtapFun({
          'removebindtap': 1
        });
        break;
      default:
        break;
    }

    /* 增加评论后
    @param commentData  评论的上下文 相关信息
    @param commentContent 评论的文本内容
    */
    function commentFun(commentData, content) {
      var data = {};
      if (commentData['type'] == 1) {
        data = {
          'self:community_api:community:comment': {
            'articleId': commentData['articleid'],
            'content': content,
            'id': commentData['id'],
            'come_from': 'zc_act',
            'commentType': 0,
            'parentUserId': commentData['parentuserid'],
            'parentCommentId': commentData['parentcommentid'],
            'pParentCommentId': commentData['pparentcommentid'],
            'relateInfo': '',
            'timestamp': timestamp['timestamp'],
            'gtk': timestamp['gtk']
          }
        }
      } else if (commentData['type'] == 2) {
        data = {
          'self:community_api:community:comment': {
            'articleId': commentData['articleid'],
            'content': content,
            'commentType': commentData['commenttype'],
            'parentUserId': commentData['parentuserid'],
            'parentCommentId': commentData['parentcommentid'],
            'pParentCommentId': commentData['pparentcommentid'],
            'relateInfo': commentData['relateinfo'],
            'relatePPInfo': commentData['relateppinfo'],
            'relatePPAccount': commentData['relateppaccount'],
            'id': commentData['id'],
            'relatePPAccountType': commentData['relateppaccounttype'],
            'timestamp': timestamp['timestamp'],
            'gtk': timestamp['gtk'],
            'come_from': 'zc_act'
          }
        }
      } else {
        data = {
          'self:community_api:community:comment': {
            'articleId': commentData['articleid'],
            'content': content,
            'commentType': commentData['commenttype'],
            'parentUserId': commentData['parentuserid'],
            'parentCommentId': commentData['parentcommentid'],
            'pParentCommentId': commentData['pparentcommentid'],
            'relateInfo': commentData['relateinfo'],
            'relatePPInfo': commentData['relateppinfo'],
            'relatePPAccount': commentData['relateppaccount'],
            'id': commentData['id'],
            'relatePPAccountType': commentData['relateppaccounttype'],
            'relatePInfo': commentData['relatepinfo'],
            'relatePAccount': commentData['relatepaccount'],
            'relatePAccountType': commentData['relatepaccounttype'],
            'timestamp': timestamp['timestamp'],
            'gtk': timestamp['gtk'],
            'come_from': 'zc_act'
          }
        }
      }

      // return false;
      request.post({
        path: '/wxapp_api/api'
      }, data)
        .then(function (res) {
          if (!!res['self:community_api:community:comment']['ret']) {
            modal.toast(res['self:community_api:community:comment']['msg']);
            return false;
          }
          var returnComment = res['self:community_api:community:comment']['data'];
          if (commentData['type'] == 1) {
            //一级留言
            //重新加载表评论列表
            that.loadComment({
              articleId: commentData.articleid,
              page: 1
            }, {}, true);
            return true;
          } else if (commentData['type'] == 2) { //二级留言            
            var newComment = commentList.commentList(returnComment, commentData);
            if (!that['data']['commentList'][commentData.index]['secondCommentInfo']['commentInfo']) {
              that['data']['commentList'][commentData.index]['secondCommentInfo'] = {
                'hasNext': 0,
                'commentInfo': [newComment]
              }
              that['data']['commentList'][commentData.index]['commentCount'] += 1;
            } else {
              that['data']['commentList'][commentData.index]['secondCommentInfo']['commentInfo'].push(newComment);
              that['data']['commentList'][commentData.index]['commentCount'] += 1;
            }

          } else { //三级留言            
            var returnComment = res['self:community_api:community:comment']['data'];
            var newComment = commentList.commentList(returnComment, commentData);
            that.data.commentList[commentData.index]['secondCommentInfo']['commentInfo'].push(newComment);
            that.data.commentList[commentData.index]['commentCount'] += 1;
          }
          that.data.articleInfo.commentCount += 1;
          that.setData({
            articleInfo: that.data.articleInfo,
            commentList: that.data.commentList
          });
        })
    }

    //点赞功能
    function like(data) {
      if (data['liketabflag'] != 0) {
        return false;
      }
      that.data.commentList[data.index]['likeTabFlag'] = 1;
      that.setData({
        commentList: that.data.commentList
      });
      var likeData = {};
      if (data['type'] == -1) {
        likeData = {
          'self:community_api:community:like': {
            'articleId': data['articleid'],
            'commentId': data['commentid'],
            'likeType': data['type'],
            'timestamp': timestamp['timestamp'],
            'gtk': timestamp['gtk'],
            'come_from': 'zc_act',
            'id': data['id']
          }
        }
      } else {
        likeData = {
          'self:community_api:community:like': {
            'articleId': data['articleid'],
            'commentId': data['commentid'],
            'likeType': data['type'],
            'relateInfo': data['relateinfo'],
            'relateAccount': data['relateaccount'],
            'id': data['id'],
            'relateAccountType': data['relateaccounttype'],
            'timestamp': timestamp['timestamp'],
            'gtk': timestamp['gtk'],
            'come_from': 'zc_act',
          }
        }
      }

      request.post({
        path: '/wxapp_api/api'
      }, likeData)
        .then(function (res) {
          if (res['self:community_api:community:like']['ret'] != 0) {
            modal.toast(res['self:community_api:community:like']['msg']);
            that.data.commentList[data.index]['likeTabFlag'] = 0;
            that.setData({
              commentList: that.data.commentList
            });
            return false;
          }
          if (data.type != 1) {
            that.data.commentList[data.index]['myLike'] = 0;
            that.data.commentList[data.index]['likeCount'] -= 1;
            that.data.commentList[data.index]['likeTabFlag'] = 0;
          } else {
            that.data.commentList[data.index]['myLike'] = 1;
            that.data.commentList[data.index]['likeCount'] += 1;
            that.data.commentList[data.index]['likeTabFlag'] = 0;
          }
          that.setData({
            commentList: that.data.commentList
          });
        })
    }

    //删除一级评论
    //
    function delStairComment(delData) {
      if (mark != 0) {
        return false;
      }
      mark = delData['commentid'];
      var data = {
        'self:community_api:community:deleteComment': {
          'commentId': delData['commentid'],
          'articleId': 0,
          'timestamp': timestamp['timestamp'],
          'gtk': timestamp['gtk']
        }
      }
      request.post({
        path: '/wxapp_api/api'
      }, data)
        .then(function (res) {
          if (res['self:community_api:community:deleteComment']['ret'] != 0) {
            modal.toast(res['self:community_api:community:deleteComment']['msg']);
            return false;
          }
          that.data.articleInfo.commentCount -= (that.data.commentList[delData.index].commentCount + 1);
          that.data.articleInfo.firstCommentCount -= 1;
          that.data.commentList.splice([delData.index], 1);
          that.setData({
            articleInfo: that.data.articleInfo,
            commentList: that.data.commentList
          });
          mark = 0;
        })
    }

    // 删除按钮展示
    function delcommentFun(data) {
      for (var i = 0; i < that.data.commentList.length; i++) {
        var commentInfo = that.data.commentList[i]['secondCommentInfo']['commentInfo'];
        if (commentInfo) {
          for (var j = 0; j < commentInfo.length; j++) {
            commentInfo[j]['isDel'] = true;
          }
        }
      }
      that.data.commentList[data.parentidx]['secondCommentInfo']['commentInfo'][data.itemidx]['isDel'] = false;
      that.setData({
        commentList: that.data.commentList,
        removeBindtap: 1
      });

    }

    //删除按钮隐藏
    function removeBindtapFun(removeFlag) {
      if (removeFlag.removebindtap == 1) {
        for (var i = 0; i < that.data.commentList.length; i++) {
          var commentInfo = that.data.commentList[i]['secondCommentInfo']['commentInfo'];
          if (commentInfo) {
            for (var j = 0; j < commentInfo.length; j++) {
              commentInfo[j]['isDel'] = true;
            }
          }
        }
        that.setData({
          commentList: that.data.commentList,
          removeBindtap: 0
        });
      }
    }

    //删除二级评论
    function delSecondComment(delSecondData) {
      if (mark != 0) {
        return false;
      }
      mark = delSecondData['commentid'];
      var data = {
        'self:community_api:community:deleteComment': {
          'commentId': delSecondData['commentid'],
          'articleId': 0,
          'timestamp': timestamp['timestamp'],
          'gtk': timestamp['gtk']
        }
      };
      request.post({
        path: '/wxapp_api/api'
      }, data)
        .then(function (res) {
          if (res['self:community_api:community:deleteComment']['ret'] != 0) {
            modal.toast(res['self:community_api:community:deleteComment']['msg']);
            return false;
          }
          that.data.commentList[delSecondData.index]['secondCommentInfo']['commentInfo'].splice([delSecondData.itemindex], 1);
          that.data.commentList[delSecondData.index]['commentCount'] -= 1;          
          that.data.articleInfo.commentCount -= 1;
          that.setData({
            articleInfo: that.data.articleInfo,
            commentList: that.data.commentList
          });
          mark = 0;
        });
    };
  },
  data: {
    show: false,
    pageData: {},
    tabIndex: 0,
    id: 0,
    commentCountPerPage: 5,//一页评论数量
    loadStatus: 0,//是否正加载，防止重复加载
    nextPage: 1,//下一页评论页码
    hasNext: 1,//是否还有更多评论
    commentList: [],//评论列表
    articleId: 0,
    hideGYDetailModal: 1,
    hideGYLayer: 1,
    showTip: false // 是否显示提示 false:不显示
  },
  onLoad: function (option) {
    var tip = wx.getStorageSync('catchTipInfo') || false; // 存储是否点击过关闭
    this.data.id = option.id;
    // 如果当前时间大于设定的时间或者已点击过关闭
    if(new Date().getTime() >= new Date('2018/2/24 00:00:00').getTime() || tip) {
      this.setData({
        showTip: false
      });
    }else{
      this.setData({
        showTip: true
      });
    }
    this.setData({
      id: this.data.id
    });
    this.loadData({
      actId: option.id
    });
  },
  onShareAppMessage: function (res) {
    return {
      title: this.data.pageData.share_title,
      path: '/pages/zc-detail/zc-detail?id=' + this.data.id,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  commentShow: function(e) {
    request.bind().then(() => {
      this.onCommentShow(e)
    })
  },
  goSku: function(e) {
    let id = e.currentTarget.dataset.id
    request.bind().then(() => {
      wx.navigateTo({
          url: '../zc-sku/zc-sku?id=' + id
      })
    })
  },
  loadData: function (option) {
    var that = this;
    var data = {
      "zp:zc_api:act:detail":
      { "id": option.actId }
    };
    modal.loading();
    request.post({
      path: '/wxapp_api/api'
    }, data).then(function (res) {
      if (res['zp:zc_api:act:detail'].ret == 0) {
        var respData = res['zp:zc_api:act:detail'].data;        
        that.data.pageData = respData;
        respData.vision = respData.vision.replace(/<br\s*\/?>/g, '\n');
        if (respData.operator_type == 2) {
          if (respData.operator_info.summary != null) {
            respData.operator_info.summary = respData.operator_info.summary.replace(/<br\s*\/?>/g, '\n');
          }
          if (respData.operator_info.achievement != null) {
            respData.operator_info.achievement = respData.operator_info.achievement.replace(/<br\s*\/?>/g, '\n');
          }
          for (var i = 0; i < respData.gongyis.length; i++) {
            if (respData.gongyis[i].desc != null) {
              respData.gongyis[i].desc = respData.gongyis[i].desc.replace(/<br\s*\/?>/g, '\n');
            }
          }
        }

        for (var i = 0; i < respData.stories.length; i++) {
          if (respData.stories[i].desc != null) {
            respData.stories[i].desc = respData.stories[i].desc.replace(/<br\s*\/?>/g, '\n');
          }
        }
        for (var i = 0; i < respData.purposes.length; i++) {
          if (respData.purposes[i].desc != null) {
            respData.purposes[i].desc = respData.purposes[i].desc.replace(/<br\s*\/?>/g, '\n');
          }
        }
        for (var i = 0; i < respData.skus.length; i++) {
          if (respData.skus[i].desc != null) {
            respData.skus[i].desc = respData.skus[i].desc.replace(/<br\s*\/?>/g, '\n');
          }
        }
        that.data.show = true;
        var option = {
          articleId: that.data.pageData.article_id,
          page: that.data.nextPage
        };
        //加载完评论后，附带需要渲染的数据
        var setData = {
          pageData: that.data.pageData,
          show: that.data.show
        }
        that.loadComment(option, setData);
        modal.hide();
      } else {
        modal.hide();
        modal.toast(res['zp:zc_api:act:detail'].msg);
      }
    });
  },
  loadComment: function (option, setData, refresh) {
    var that = this;
    if (setData == undefined) {
      setData = {};
    }
    option.pageSize = that.data.commentCountPerPage;
    //开始加载
    that.data.loadStatus = 1;
    request.post({
      path: '/wxapp_api/api'
    }, { "self:community_api:community:commentList": option }).then(function (resp) {
      if (resp['self:community_api:community:commentList'].ret == 0) {
        var respData = resp['self:community_api:community:commentList'].data;
        //结束加载
        that.data.loadStatus = 0;
        setData.loadStatus = that.data.loadStatus;
        //文章信息
        that.data.articleInfo = respData.articleInfo;
        setData.articleInfo = that.data.articleInfo;
        //下页页码
        that.data.nextPage = respData.page + 1
        setData.nextPage = that.data.nextPage;
        //是还有一页
        that.data.hasNext = respData.hasNext;
        setData.hasNext = that.data.hasNext;
        //评论列表        
        if (refresh != undefined && refresh == true) { //重新刷评论列表
          that.data.commentList = [];
          setData.tabIndex = 1; //切到留言列表
        }
        for (var i = 0; i < respData.commentList.length; i++) {
          respData.commentList[i]['userInfo']['face'] = filter.filter(respData.commentList[i]['userInfo']['face']);
          respData.commentList[i]['content'] = filter.filter(respData.commentList[i]['content']);
          respData.commentList[i]['createTime'] = formatTime.formatTime(respData.commentList[i]['createTime']);
          respData.commentList[i]['likeTabFlag'] = 0;
          that.data.commentList.push(respData.commentList[i]);
        }
        setData.commentList = that.data.commentList;
        //渲染数据           
        that.setData(setData);
      } else {
        modal.toast(res['self:community_api:community:commentList'].msg);
      }
    });
  },
  changeTab: function (ev) {
    var targetTabIndex = ev.currentTarget.dataset.index;
    if (targetTabIndex == 0 || this.data.articleInfo.commentCount > 0) {
      this.data.tabIndex = targetTabIndex;
      this.setData({
        tabIndex: this.data.tabIndex
      });
    }
  },
  //滑动加载评论
  pullLoad: function () {
    var that = this;
    if (that.data.tabIndex == 1 && that.data.loadStatus == 0 && that.data.hasNext == 1) {//只有用户停留在留言列表且还有下一页且没有在加载才加载
      var option = {};
      option.articleId = that.data.pageData.article_id;
      option.page = that.data.nextPage;
      option.pageSize = that.data.commentCountPerPage;
      that.loadComment(option);
    }
  },
  makeCall: function (ev) {
    wx.makePhoneCall({
      phoneNumber: ev.currentTarget.dataset.phone,
    })
  },
  // 公益弹窗
  gongyiDeatailShow: function () {
    this.data.hideGYDetailModal = 0;
    this.setData({
      hideGYDetailModal: this.data.hideGYDetailModal
    });
  },
  //隐藏弹窗
  gongyiDeatailHide: function () {
    this.data.hideGYDetailModal = 1;
    this.setData({
      hideGYDetailModal: this.data.hideGYDetailModal
    });
  },
  hideGongyiLayer: function () {
    this.data.hideGYLayer = 1;
    this.setData({ hideGYLayer: this.data.hideGYLayer });
  },
  showGongyiLayer: function () {
    this.data.hideGYLayer = 0;
    this.setData({ hideGYLayer: this.data.hideGYLayer });
  },
  stopPropagation: function () {
    //用catchtap停止冒泡
  },
  // 关闭提示
  closeTipFn: function() {
    wx.setStorageSync('catchTipInfo', true);
    this.setData({
      showTip: false
    });
  }
};
utils.assign(pageSetting, comment, goTop);
Page(pageSetting)